<template>
  <div class="page-common-layout">
    <div class="page-common-left" style="width:400px;padding: 0">
      <div class="header">
        <span class="title">{{
          $ct("mdataOrganizationIndex", "组织机构")
        }}</span>
        <span>
          <!-- <a-icon type="more" @click="openOrgView" /> -->
        </span>
      </div>
      <div class="padding-xs">
        <a-input-search
          placeholder="组织机构名称"
          style="width: 100%"
          @search="onSearch"
        />
      </div>
      <div class="body">
        <ZTree
          ref="masterList"
          :columns="columns"
          rowKey="uuid"
          :url="url"
          :parameter="parameter"
          :masterMust="false"
          :formatConditions="false"
          :showSearch="false"
          :loadAll="true"
          treeText="orgName"
          :expandAll="false"
          @rowClick="
            (e) => {
              masterRowClick(e);
            }
          "
          :isFirst="true"
          @chengTreeData="chengTreeData"
        >
        </ZTree>
      </div>
    </div>
    <div class="page-common-content">
      <!-- @reset="
          () => {
            (subQueryParam = { roleName: '', roleCode: '' }),
              $refs.subList.refresh(true);
          }
        " -->
      <tool-bar @search="$refs.subList.refresh(true)" @reset="handleReset()">
        <template slot="toolBtn" slot-scope="scope">
          <a-button
            v-action:authGroup_add
            class="cu-btn-primary"
            icon="plus"
            @click="handleAdd('1', $refs.masterList.data, 'sub')"
          >
            新建岗位角色
          </a-button>
          <!-- <a-button icon="download" type="link" @click="handDownload()"
            >导出</a-button
          > -->
          <!-- <a-button
					  class="cu-btn-primary"
					  icon="plus"
					  @click="handleAccessAuth('all', 1)"
					  >{{$ct("batchLicensing","批量授权")}}</a-button
					> -->
        </template>
        <template slot="toolForm">
          <a-form-item label="岗位角色名称">
            <a-input
              v-model="subQueryParam.roleName"
              placeholder="岗位角色名称"
            />
          </a-form-item>
          <a-form-item label="岗位角色编码">
            <a-input
              v-model="subQueryParam.roleCode"
              placeholder="岗位角色编码"
            />
          </a-form-item>
        </template>
      </tool-bar>
      <DataGrid
        ref="subList"
        type="sub"
        :url="url"
        :columns="subColumns"
        :queryParam="subQueryParam"
        rowKey="uuid"
        showPagination="auto"
        :showRowSelect="false"
        @rowClick="
          (e) => {
            subRowClick(e);
          }
        "
        v-if="showPage"
      >
        <span slot="renderRoleStatus" slot-scope="{ text }">
          <a-tag :color="text === 'MenuStatus.01' ? 'green' : 'red'">
            {{
              text === "MenuStatus.01"
                ? $ct("enable", "启用")
                : $ct("disable", "禁用")
            }}
          </a-tag>
        </span>
        <span slot="renderAction" slot-scope="{ text, record }">
          <template>
            <a
              @click="handleEdit(record, $refs.masterList.data, 'sub')"
              v-action:authGroup_edit
            >
              {{ $ct("edit", "编辑") }}
            </a>
            <!-- <template v-if="record.uuid !== '402888e5575f3ab7015760002082076e'"> -->
            <span class="action-margin"></span>
            <a
              @click="handleSub(record, 'sub')"
              :class="record.id == 34 ? 'a-disabled' : 'action-delete'"
              v-action:authGroup_delete
            >
              {{ $ct("delete", "删除") }}
            </a>
            <!-- </template> -->
            <a-dropdown>
              <a class="ant-dropdown-link">
                授权
                <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a @click="empower('web', record)">授权WEB端</a>
                </a-menu-item>
                <!-- <a-menu-item>
									<a @click="empower('web',record)">授权WEB端</a>
								</a-menu-item> -->
                <a-menu-item>
                  <a @click="empower('app', record)">授权APP端</a>
                </a-menu-item>
                <!-- <a-menu-item>
									<a @click="empower('data',record)">数据授权</a>
								</a-menu-item> -->
                <a-menu-item>
                  <a @click="empower('user', record)">授权用户</a>
                </a-menu-item>
                <!-- <a-menu-item>
									<a @click="empower('user',record)">授权用户</a>
								</a-menu-item> -->
                <a-menu-item>
                  <a @click="handleProjectDrawer(record)">授权数据权限</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </span>
      </DataGrid>
      <editForm
        ref="subModal"
        :visible="subVisible"
        :loading="subConfirmLoading"
        :model="subMdl"
        @cancel="handleCancel('sub')"
        @ok="handleOk('sub')"
      />

      <org-preview
        ref="viewOrgModal"
        :visible="viewOrgVisible"
        @cancel="viewOrgVisible = false"
      >
      </org-preview>

      <preview-image
        :visible.sync="visibleViewImg"
        :imgSrc="imgSrc"
      ></preview-image>

      <empower-modal
        ref="empowerModal"
        :key="empowerKey"
        :visible="empowerVisible"
        :rowData="rowData"
        @cancel="empowerCancel"
      >
      </empower-modal>
      <!-- 项目抽屉 -->
      <projectDrawer
        :visible.sync="projectDrawerVisible"
        :parameter="rowData"
      ></projectDrawer>
    </div>
  </div>
</template>
<script>
import { TreeGrid, DataGrid, ZTree, ExportData } from "@/components";
import { treeGridMixin } from "@/mixins/treeGridMixin";
import editForm from "./edit.vue";
import empowerModal from "./empowerModal.vue";
import orgPreview from "@/components/TopVUI/custom/orgPreview.vue";
import previewImage from "@/components/TopVUI/custom/previewImage.vue";
//项目抽屉
import projectDrawer from "./projectDrawer.vue";

import Vue from "vue";
import { baseUrl } from "@/services/baseUrl.js";
import { ACCESS_TOKEN } from "@/store/mutation-types";

export default {
  mixins: [treeGridMixin],
  components: {
    editForm,
    TreeGrid,
    DataGrid,
    orgPreview,
    previewImage,
    ExportData,
    empowerModal,
    projectDrawer,
    ZTree,
  },
  data() {
    return {
      key: "1",
      columns: [
        {
          title: "组织机构",
          align: "left",
          dataIndex: "text",
          langCode: "mdataOrganizationIndex",
        },
      ],
      subColumns: [
        {
          title: "岗位角色名称",
          dataIndex: "roleName",
          width: 300,
        },
        {
          title: "岗位角色编码",
          dataIndex: "roleCode",
          width: 150,
        },
        {
          title: "岗位角色状态",
          align: "center",
          dataIndex: "roleStatus",
          scopedSlots: { customRender: "renderRoleStatus" },
          width: 80,
        },
        {
          title: "岗位角色排序",
          align: "center",
          dataIndex: "roleSort",
          width: 80,
        },
        {
          title: "操作",
          align: "center",
          dataIndex: "action",
          width: 150,
          scopedSlots: {
            customRender: "renderAction",
          },
          fixed: "right",
        },
      ],
      masterVisible: false,
      subVisible: false,
      masterConfirmLoading: false,
      subConfirmLoading: false,
      masterMdl: null,
      subMdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      subQueryParam: {},
      url: {
        fathersUrl: "/mdata/organization/getRoleTreeSysOrganization",
        subList: "/system/sysRole/getPageSet",
        subSave: "/system/sysRole/save",
        subUpdate: "/system/sysRole/update",
        subDelete: "/system/sysRole/delete",
      },
      parameter: {
        father: {
          levelId: 1,
          pid: 1,
        },
        children: {},
      },
      postQueryParam: {},
      searchTree: [],
      showMenu: false,
      viewOrgVisible: false,
      visibleViewImg: false,
      imgSrc: "",
      empowerVisible: false,
      rowData: {},
      empowerKey: "1",
      //授权项目
      projectDrawerVisible: false,
      projectDrawerKey: "123456789",
      //
      showPage: false,
    };
  },
  activated() {},
  filters: {
    sexFilter(sex) {
      const sexMap = {
        "UserSex.01": "男",
        "UserSex.02": "女",
        "UserSex.03": "未知",
      };
      return sexMap[sex];
    },
    statusFilter(status) {
      const statusMap = {
        "UserInfoStatus.01": "正常",
        "UserInfoStatus.02": "锁定",
        "UserInfoStatus.03": "禁用",
        "UserInfoStatus.04": "离职",
        "UserInfoStatus.05": "注销",
        "UserInfoStatus.06": "删除",
      };
      return statusMap[status];
    },
  },
  methods: {
    handleReset() {
      this.subQueryParam.roleName = "";
      this.subQueryParam.roleCode = "";
      this.$refs.subList.refresh(true);
    },

    //树组件数据加载完成触发
    chengTreeData(data) {
      this.showPage = true;
    },
    handleProjectDrawer(record) {
      this.rowData = record;
      this.projectDrawerVisible = true;
    },

    getOrgTree() {
      this.$post("/mdata/organization/getTreeSysOrganization").then((res) => {
        this.treeData = JSON.parse(JSON.stringify(res));
        this.searchTree = JSON.parse(JSON.stringify(res));
        this.showMenu = true;
      });
    },
    masterRowClick(record) {
      this.$refs.masterList.rows = record;
      this.subQueryParam.orgId = record.id;
      this.postQueryParam = {};
      this.$refs.subList?.refresh();
    },
    subRowClick(record) {
      this.postQueryParam.orgId = record.orgId;
      this.postQueryParam.userNameId = record.userNameId;
    },
    // 重置密码
    resetPassword() {
      if (this.$refs.subList.selectedRows.length === 0) {
        this.$message.warn("请先勾选需要操作的用户");
      } else {
        let uuid = [],
          password = [];
        this.$refs.subList.selectedRows.forEach((req, index) => {
          uuid.push(req.uuid);
          password.push(req.userNameId);
        });
        this.$post("/mdata/user/updatePassword", {
          uuid: uuid.toString(),
          password: password.toString(),
        }).then((res) => {
          if (res.statusCode === 200) {
            this.$message.success(res.message);
            this.$refs.subList.refresh();
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },
    //菜单搜索
    onSearch(value) {
      this.$refs.masterList.data = this.treeFilter(
        value,
        JSON.parse(JSON.stringify(this.$refs.masterList.originalData))
      );
    },
    selectTree(value, node, extra) {
      this.subQueryParam.orgId = value[0];
      this.$refs.subList.refresh(true);
    },
    //树形数据过滤
    treeFilter(value, arr) {
      if (!arr) {
        return [];
      }
      let newarr = [];
      arr.forEach((item) => {
        if (item.orgName.indexOf(value) > -1) {
          let redata = this.treeFilter(value, item.children);
          let obj = {
            ...item,
            children: redata,
          };
          newarr.push(obj);
        } else {
          if (item.children && item.children.length > 0) {
            let redata = this.treeFilter(value, item.children);
            let obj = {
              ...item,
              children: redata,
            };
            if (redata && redata.length > 0) {
              newarr.push(obj);
            }
          }
        }
      });
      return newarr;
    },
    openOrgView() {
      this.viewOrgVisible = true;
      this.$refs.viewOrgModal.getOrgData(this.$refs.masterList.data);
    },
    preViewHeadPortrait(val) {
      this.imgSrc = val;
      this.visibleViewImg = true;
    },
    empower(val, record) {
      this.rowData = record;
      let title = "";
      if (val === "web") {
        title = "授权WEB菜单";
        this.$refs.empowerModal.getList(record, "web");
      } else if (val === "app") {
        title = "授权APP端";
        this.$refs.empowerModal.getList(record, "app");
      } else if (val === "user") {
        title = "授权用户";
        this.$refs.empowerModal.getList(record, "user");
      } else if (val === "data") {
        title = "数据授权";
        this.$refs.empowerModal.getList(record, "data");
      } else if (val === "user") {
        title = "授权用户";
        this.$refs.empowerModal.getList(record, "user");
      }
      this.empowerVisible = true;
      this.$refs.empowerModal.title = title;
      this.$refs.empowerModal.loadingText = "正在加载数据...";
    },
    empowerCancel() {
      this.empowerVisible = false;
      this.empowerKey = new Date().getTime();
    },
    handDownload() {
      window.location.href =
        baseUrl +
        "/mdata/user/exportSysRole" +
        "?token=" +
        Vue.ls.get(ACCESS_TOKEN);
    },
  },
};
</script>

<style scope lang="less">
.business-license {
  cursor: pointer;
  padding: 5px;
  height: 36px !important;
  width: 36px !important;
}
.page-common-left {
  display: flex;
  flex-direction: column;
  .header {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ebeef5;
    color: #606266;
    padding: 10px;
    height: 50px;
    box-sizing: border-box;

    .title {
      font-size: 16px;
    }
  }

  .body {
    padding: 10px;
    overflow: auto;
    flex: 1;
  }
}
</style>
